package com.macrounion.atv.processor;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import com.google.common.collect.Lists;
import com.macrounion.atv.cache.CurrentDataCache;
import com.macrounion.atv.service.entity.CurrentData;
import com.macrounion.base.service.utils.DateUtils;
import org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.macrounion.atv.cache.DeviceCache;
import com.macrounion.atv.service.dto.req.DeviceReqDto;
import com.macrounion.atv.service.dto.req.DeviceStatusReqDto;
import com.macrounion.atv.service.dto.resp.DeviceListRespDto;
import com.macrounion.atv.service.entity.Channel;
import com.macrounion.atv.service.entity.Device;
import com.macrounion.atv.service.entity.ext.DeviceStatusExt;
import com.macrounion.atv.service.service.ChannelService;
import com.macrounion.atv.service.service.DeviceService;
import com.macrounion.base.processor.BaseProcessor;
import com.macrounion.base.service.dto.PageRespDto;
import com.macrounion.base.service.exception.BusinessException;

@Component
public class DeviceProcessor extends BaseProcessor<Device, Device, DeviceService, Device> {

    @Autowired
    private CurrentDataCache currentDataCache;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private DeviceCache deviceCache;

    public List<Device> getDeviceBySpotId(String spotId){
        return service.getDeviceBySpotId(spotId);
    }

    public PageRespDto<DeviceListRespDto> getDeviceList(DeviceReqDto deviceReqDto){
        PageRespDto<DeviceListRespDto> pageResp = new PageRespDto();
        PageHelper.startPage(deviceReqDto.getPageInfo().getPageIndex(),deviceReqDto.getPageInfo().getPageSize());
        Page<DeviceListRespDto> pm=(Page<DeviceListRespDto>) service.getDeviceList(deviceReqDto);
        BeanUtils.copyProperties(pm, pageResp);
        pageResp.setDataList(pm.getResult());
        return pageResp;
    }

    @Transactional
    @Override
    public Device save(Device reqDto) {
        //检查通信识别码不能重复
        int findCount=service.findCount(reqDto);
        if(findCount>0)
            throw new BusinessException(201,"通信识别码已经存在");
        if(!StringUtils.isEmpty(reqDto.getId()))
        	deviceCache.remove(reqDto.getId());
        Device d = super.save(reqDto);
        deviceCache.putDevice(d);
        return d;
    }


	
    public List<Device> getAllDevice(){
    	List<Device> resp = service.getAllDevice(new Device());
		resp.forEach(r->{
			deviceCache.putDevice(r);
		});
		return resp;
    }
    public PageRespDto<DeviceStatusExt> getStatusList( DeviceStatusReqDto deviceStatusReqDto){
        PageRespDto<DeviceStatusExt> pageResp = new PageRespDto<DeviceStatusExt>();
        if(CollectionUtils.isEmpty(deviceStatusReqDto.getSpotIds()) && !StringUtils.isEmpty(deviceStatusReqDto.getSpotId())){
            List<String> spotIds=Lists.newArrayList();
            spotIds.add("");
            deviceStatusReqDto.setSpotIds(spotIds);
        }

        PageHelper.startPage(deviceStatusReqDto.getPageInfo().getPageIndex(),deviceStatusReqDto.getPageInfo().getPageSize());
        Page<DeviceStatusExt> pm=(Page<DeviceStatusExt>) service.getDeviceStatus(deviceStatusReqDto);

        for(DeviceStatusExt dev : pm.getResult()) {

            if(dev.getChannelTimout()==0){
                dev.setDeviceRstatus(1);
                continue;
            }

            List<CurrentData> list=new ArrayList<>(currentDataCache.getCurrentData(dev.getDeviceId()));
            if(CollectionUtils.isEmpty(list)){
                dev.setDeviceRstatus(1);
            }else{

                list.sort(Comparator.comparing(CurrentData::getCreatedTime).reversed());//sort降序
                CurrentData currentData=list.get(0);
                Date now=new Date();//现在的时间


                //int res = date1.compareTo(date2)，相等则返回0，date1大返回1，否则返回-1。
                int res = DateUtils.addMinute(currentData.getCreatedTime(),(dev.getTimeout()==null ? 0: dev.getTimeout())).compareTo(now);

//                if(DateUtils.addMinute(currentData.getCreatedTime(),dev.getTimeout()).before(now)) {
               if (res == -1) {
                    dev.setDeviceRstatus(0);
                }
                else {
                    dev.setDeviceRstatus(1);
                }
            }

        }



        BeanUtils.copyProperties(pm, pageResp);
        pageResp.setDataList(pm.getResult());
        return pageResp;
    }

	@Override
	@Cacheable(value="devices",key="#id")
	public Device findById(String id) {
		// TODO Auto-generated method stub
		return super.findById(id);
	}

    @Transactional
	@Override
	@Caching(evict = { 
			@CacheEvict(value="devices",key="#id"),
			@CacheEvict(value="currentdatas",key="#id") })
	public boolean removeById(String id) {
		// TODO Auto-generated method stub
        //判断设备下是否有通道，有通道则不能删除
        List<Channel> channels=channelService.getChannelListByDevice(id,"",null);
        if(channels!=null && channels.size()>0)
            throw new BusinessException(201,"该设备下仍有通道，不能删除");
        deviceCache.remove(id);
		return super.removeById(id);
	}

    public List<Device> getDevicesToVisual(Device device){
        List<Device> resp = service.getDevicesToVisual(device);
        return resp;
    }

}